/*
 * @Description: 签章相关一些适配
 */
import { SIGN_PARAMS } from './const';
import { useBaseInfoWithOut } from '@/store/modules/base-info';
import { useTemplateWithOut } from '@/store/modules/template';
import globalData, {BodyTypeEnums} from '@/plugins/data';
import globalMethods from '@/plugins/methods';
import {isOfficeBodyType, officeSignature} from "@/plugins/office";
import {checkOFDComplete} from "@/plugins/office/extend/ofd-office";
import {useSummaryTabWithOut} from "@/store/modules/summary/tab";
import {fireEvent, getCollEventParams} from "@/handles/common/sdk";

const useBaseInfo = useBaseInfoWithOut();
const useTemplate = useTemplateWithOut();
const summaryTab = useSummaryTabWithOut();
/**
 * @description: 一进页面就设置
 * @param {Object} baseInfo 基础信息对象
 * @return {*}
 */
export function initParams(baseInfo) {
    const {
        affair: { state: affairState },
    } = baseInfo.businessData;

    //签过章保存在正文了，一进来就有签章悬浮的这种情况要用
    //需要有这个参数，签章才能删除、查看详情。
    window.affairState = affairState;
}

//将签章需要参数设置在window上
function setGlobalParams({
    nodeName,
    secretLevelAble,
    isCAP4,
    forwardMember,
    bodyType,
    subState,
    signetProtectInput,
}) {
    const { openFrom } = globalData;
    const params = {
        openFrom,
        isFormQuery: false,
        isFormStatic: false,
        isFromTrace:
            openFrom == 'repealRecord' ||
            openFrom == 'stepBackRecord' ||
            openFrom == 'stepbackRecord',
        secretLevelAble,
        nodeName,
        isCAP4,
        forwardMember,
        bodyType,
        subState,
        signetProtectInput,
    };
    SIGN_PARAMS.forEach((d) => {
        window[d] = params[d];
    });
}

function checkYozo(bodyType) {
    var isYozoWps = false;
    if (bodyType && (bodyType == '43' || bodyType == '44')) {
        isYozoWps = true;
    }
    if (isYozoWps && window?.isYoZoOffice()) {
        //对不起，您本地的永中office软件不支持对当前正文格式的此操作！
        globalMethods.error({content:globalMethods.i18n('collaboration.alertWpsYozoOffice_modify')});
        return true;
    }
    return false;
}
//是否指定回退者
function isSpecifiesBack(subState) {
    if (subState == '15' || subState == '17') {
        globalMethods.error({
            content: globalMethods.i18n('collaboration.alert.CantModifyBecauseOfAppointStepBack'),
        });
        mainbody_callBack_failed();
        return true;
    }
}
function isChrome49() {
    try {
        var ua = navigator.userAgent;
        if (
            ua.indexOf('Chrome') != -1 &&
            ua.match(/chrome\/[\d.]+/gi)[0].indexOf('Chrome/49') != -1
        ) {
            return true;
        }
    } catch (e) {}
    return false;
}

function summaryChange(bodyType) {
    if (
        bodyType &&
        (bodyType == '41' || bodyType == '42' || bodyType == '43' || bodyType == '44') &&
        isChrome49()
    ) {
        return;
    }
    $.confirmClose();
}

function isChinaOs() {
    if (
        !navigator.appName == 'Microsoft Internet Explorer' ||
        navigator.userAgent.indexOf('Trident') != -1
    ) {
        return String(navigator.platform).indexOf('Linux') > -1;
    }
    return false;
}

//以下代码是搬过来的。从briefSummary.js
/**
 * 1、HTML编辑状态不能盖章
 * 2、对修改正文的地方增加限制：已经加盖了专业签章的地方不能修改正文
 * 3、表单数据域保护
 */
export async function openSignature() {
    const businessData = useBaseInfo.baseInfo.businessData;
    let hook = await fireEvent('sign', getCollEventParams(businessData, globalData));
    if (!hook) {
        return;
    }
    summaryTab.changeActiveIndex(0);
    const zwIframe = useTemplate.zwIframe.contentWindow;
    const {
        summary: { id: summaryId, forwardMember, signetProtectInput },
        affair: { subState, nodeName, state: affairState, affairMemberName, memberId , bodyType },
        currentUser: { id: currentUserId },
    } = businessData;
    const secretLevelAble = businessData.pluginInfo.includes('secretLevel');
    const isCAP4 = useBaseInfo.baseInfo.zwIframe.isCap4;
    const canSign=true;
    //加进window对象，不然签不起
    setGlobalParams.call(this, {
        nodeName,
        secretLevelAble,
        affairState,
        isCAP4,
        forwardMember,
        bodyType,
        subState,
        signetProtectInput,
    });

    //永中office不支持wps正文修改
    if (checkYozo(bodyType)) {
        return;
    }
   let useWebOffice = zwIframe.useWebOffice && zwIframe.OfficeUtils.canUseWebOffice();
    //流版签文件类型的，不含pdf
    if (isOfficeBodyType(bodyType) && useWebOffice) {
        let hasNoOfficePlugin = !$.ctx.hasPlugin("officeOcx") && !$.ctx.hasPlugin("domestic");
        if (hasNoOfficePlugin) {
            globalMethods.error({content: globalMethods.i18n('office.plugin.notsupport')});
            return;
        }
        let result = await officeSignature({zwIframe, bodyType});
        console.log('OfficeBodyType',result);
    }
    //pdf在线编辑时候签章
    if (useWebOffice && `${bodyType}` === BodyTypeEnums.pdf.toString()) {
        let result = await officeSignature({zwIframe, bodyType});
        console.log('pdf',result);
    }
    
    //国产化环境，使用金格控件时，点击签章应该提示不支持
    if (isChinaOs() && $(zwIframe)[0].OfficeAPI) {
        if (bodyType == '45') {
            //国产环境下pdf协同提示：PDF兼容模式下不支持盖章
            globalMethods.error({content:globalMethods.i18n('collaboration.alert.pdfnotsupport')});
            return;
        }
        if ($(zwIframe)[0].OfficeAPI.officeType == 'kinggrid') {
            globalMethods.error({content:globalMethods.i18n('collaboration.alert.notsupport')});
            return;
        }
    }

    if (isSpecifiesBack(subState)) {
        return;
    }
    //添加正文锁
    var lockWorkflowRe = lockWorkflow(summaryId, currentUserId, 15);
    if (lockWorkflowRe[0] == 'false') {
        // V5-20223 pc端 ofd正文协同点击修改正文，批注后再点击盖章，提示他人正在修改流程
        // 0. 获取当前所有正文锁
        let locks = callBackendMethod('colManager', 'getSummaryLock', summaryId);
        // 1. 判断当前有无本人 action = -1 的锁
        let flag = true;
        if (locks != null) {
            for (let i = 0; i < locks.length; i++) {
                if (locks[i].owner == currentUserId && locks[i].action == -1) {
                    flag = false;
                }
            }
        }
        // 2. 如果有本人 action = -1 的锁, 表示当前是通过多人编辑读写锁逻辑添加的自己的写锁, 也就本人先修改正文再签章， 不应该弹出提示
        if (flag) {
            globalMethods.error({content:lockWorkflowRe[1]});
            return;
        }
    }
    //表单正文和HTML标准正文加盖isignaturehtml专业签章
    if (bodyType == '10' || bodyType == '20') {
        try {
            if (!zwIframe.isInstallIsignatureHtml()) {
                globalMethods.error(
                    {content:globalMethods.i18n('collaboration.client.not.installed.professional.signature')}
                );
                releaseWorkflowByAction(summaryId, currentUserId, 15);
                return;
            }
            if (bodyType == '20') {
                zwIframe.getFieldVals4hw(null, function (msg, form) {
                    const { displayStr, valueStr } = form;
                    zwIframe.doSignature([displayStr, valueStr]);
                });
            } else {
                zwIframe.doSignature([]);
            }
        } catch (e) {
            globalMethods.error(
                {
                    content:globalMethods.i18n('collaboration.client.not.installed.professional.signature')
                }
            );
            releaseWorkflowByAction(summaryId, currentUserId, 15);
            return false;
        }
    } else {
        var officeparamDiv = $(zwIframe.document).find('.officeparam');
        officeparamDiv.attr('style', '');

        var _officeTransIframe = $(zwIframe)[0].$('#officeTransIframe');
        var _officeEditorFrame = $(zwIframe)[0].$('#officeEditorFrame');

        var paramStr = officeparamDiv.attr('param');
        if (paramStr) {
            var paramObj = $.parseJSON('{' + paramStr + '}');

            if (bodyType == '45') {
                $(zwIframe)[0].PdfAPI.initPdf({
                    webRoot : paramObj.webRoot,
                    fileId : paramObj.fileId,
                    officecanSaveLocal : "true",
                    officecanPrint : "true",
                    needReadFile : true,
                    editType : "2,0",
                    actionCanSign: canSign,
                    createDate : paramObj.createDate,
                    callback: async function (res) {
                        if(res) {
                            await $(zwIframe)[0].PdfAPI.pdfFullSize();
                            await $(zwIframe)[0].PdfAPI.modifyContent(canSign);
                        }
                    }
                });
            } else {
                // WebOffice加载时,点击签章时需要重新加载
                if ($(zwIframe)[0].OfficeAPI.officeType === 'weboffice' &&
                  $(zwIframe) [0].useWebOffice == false) {
                    const param = {
                        ...$(zwIframe)[0].OfficeAPI.options,
                        canSign: true,
                    }
                    await $(zwIframe)[0].OfficeAPI.initOffice(param);
                }
                await($(zwIframe)[0].OfficeAPI.showOffice({
                    fileId: paramObj.fileId,
                    fileName: paramObj.fileName,
                    createDate: paramObj.createDate,
                    officeOcxUploadMax: paramObj.officeOcxUploadMax,
                    handWriteCurrentUserId: currentUserId,
                    editType:"2,0",
                    fileType:paramObj.fileType,
                    actionCanSign : true,
                    officecanSaveLocal : paramObj.officecanPrint,
                    officecanPrint : paramObj.officecanPrint,
                    initOfficeSucessCallback: function (type) {
                        if (isChinaOs() && (type == "kinggrid")) {
                            globalMethods.error(
                              {content:globalMethods.i18n('collaboration.alert.notsupport')}
                            );
                            return;
                        }
                    }
                }));
            }

            const v3x = v3x || new V3X();
            if (v3x.isChrome || v3x.isMSIE) {
                window.setTimeout(async function () {
                    if ($(zwIframe)[0].OfficeAPI && $(zwIframe)[0].OfficeAPI.officeType != 'wps') {
                        _officeTransIframe.remove();
                    }
                    $(zwIframe)[0].$('#officeFrameDiv').attr('style', 'width:100%;height:100%');
                    _officeEditorFrame.attr('width', '100%');
                    _officeEditorFrame.attr('height', '100%');

                    if (bodyType != '45') {
                        $(zwIframe)[0].OfficeAPI.setOptions({
                            affairMemberId: memberId,
                            affairMemberName,
                        });

                        await $(zwIframe)[0].OfficeAPI.WebOpenSignature();
                    }
                    zwIframe.$('#viewState').val('1');
                }, 3000);
            }
        } else {
            $(zwIframe)[0].$('#officeFrameDiv').attr('style', 'display:none;height:100%');
            // if($(zwIframe)[0].OfficeAPI.officeType == "kinggrid"){ 还原代码
            _officeTransIframe.remove();
            // }
            $(zwIframe)[0].$('#officeFrameDiv').show();

            if (bodyType == '45') {
                if($(zwIframe)[0].PdfAPI.options.pluginType === $(zwIframe)[0].PdfAPI.pluginTypes.WPS_JSSDK) {
                    let settings = await $(zwIframe)[0].PdfUtils.getPluginsSettings({ webRoot: `${_ctxPath}` });
                    if(settings.webOfficeConfig.kingsoftWebofficePcPDF == false) {
                        await $(zwIframe)[0].PdfAPI.initPdf({
                            ...$(zwIframe)[0].PdfAPI.options,
                            canSign: true,
                        })
                    }
                } else {
                    await $(zwIframe)[0].PdfAPI.pdfFullSize();
                    await $(zwIframe)[0].PdfAPI.modifyContent(true);
                }
            } else if (bodyType == '46') {
                //ofd点聚签章
                var ofdAPI = $(zwIframe)[0].OfdAPI;
                var params = zwIframe.ofdTransParms;
                params.canSign=true;
                if (params.ofdReader === "dj" ||!ofdAPI.hasOpenOfdComplete()) {
                    ofdAPI.initOfd(params);
                }
                if (await checkOFDComplete({zwIframe})){
                    ofdAPI.signOfdSeal();
                }
            } else {
                $(zwIframe)[0].OfficeAPI.setOptions({
                    affairMemberId: memberId,
                    affairMemberName,
                });

                // WebOffice加载时,点击签章时需要重新加载
                if ($(zwIframe)[0].OfficeAPI.officeType === 'weboffice' &&
                  $(zwIframe) [0].useWebOffice == false) {
                    const param = {
                        ...$(zwIframe)[0].OfficeAPI.options,
                        canSign: true,
                    }
                    await $(zwIframe)[0].OfficeAPI.initOffice(param);
                } else {
                    await $(zwIframe)[0].OfficeAPI.loadOffice(false);
                }
                await $(zwIframe)[0].OfficeAPI.WebOpenSignature(true);
                await $(zwIframe)[0].OfficeAPI.updateOfficeState("1,0");//
            }
            zwIframe.$('#viewState').val('1');
        }
    }
    summaryChange(bodyType);
    //设置正文为编辑状态
}
var ofdLoadTimes_n=1;
function checkCollOfdLoaded(ofdAPI,callback) {
    if (ofdLoadTimes_n>50){
        return;
    }
    if (ofdAPI && ofdAPI.hasOpenOfdComplete()){
        if (callback){
            callback();
        }
    }else{
        ofdLoadTimes_n++;
        setTimeout(function () {
            checkCollOfdLoaded(ofdAPI,callback);
        },3000);
    }
}
